﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using XiDianChangAn.OA.Model;

namespace XiDainChangAn.OA.EFDAL
{
    /// <summary>
    /// 职责：BaseDal封装了所有Dal的公共的增删查改
    /// 类的职责一定要单一
    /// </summary>
    public class BaseDal<T> where T : class, new()//约束T，1是个类，2，有默认的构造函数
    {
        //此类中可以封装针对数据库表数据的增删查改
        //DataModelContainer DB = new DataModelContainer();

        //依赖抽象编程
        public DbContext DB
        {
            //这里用到了简单工厂模式
            get { return DBContextFactory.GetCurrentDbContext(); }
        }

        public T GetById(int id)
        {
            return DB.Set<T>().Find(id);
        }

        public IQueryable<T> GetEntitys(Expression<Func<T, bool>> whereLambda)
        {
            return DB.Set<T>().Where(whereLambda).AsQueryable();
        }

        public IQueryable<T> GetPageEntitys<S>(int pageSize, int pageIndex, out int total, bool isAsc, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderByLambda)
        {
            total = DB.Set<T>().Where(whereLambda).Count();
            if (isAsc)
            {
                var temp = DB.Set<T>().Where(whereLambda)
                .OrderBy<T, S>(orderByLambda)
                .Skip(pageSize * (pageIndex - 1))
                .Take(pageSize);
                return temp;
            }
            else
            {
                var temp = DB.Set<T>().Where(whereLambda)
                .OrderByDescending<T, S>(orderByLambda)
                .Skip(pageSize * (pageIndex - 1))
                .Take(pageSize);
                return temp;
            }

        }

        #region 01，新增+T Add(T entity)
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="T"></param>
        /// <returns></returns>
        public T Add(T entity)
        {
            DB.Set<T>().Add(entity);
            //DB.SaveChanges();
            return entity;
        }
        #endregion

        #region 02，修改+bool UpDate(T entity)
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="T"></param>
        /// <returns></returns>
        public bool UpDate(T entity)
        {
            DB.Entry(entity).State =EntityState.Modified;
            //return DB.SaveChanges() > 0;
            return true;
        }
        #endregion

        #region 03，删除+bool Delete(T entity)
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="T"></param>
        /// <returns></returns>
        public bool Delete(T entity)
        {
            DB.Set<T>().Remove(entity);
            //return DB.SaveChanges() > 0;
            return true;
        }
        #endregion
    }
}
